package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysTenant;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.mapper.SysTenantMapper;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysTenantService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * @Description: 租户实现类
 * @author: jeecg-boot
 */
@Service("sysTenantServiceImpl")
@Slf4j
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    ISysUserService userService;
    @Autowired
    ISysRoleService roleService;
    @Autowired
    ISysUserRoleService userRoleService;

    @Override
    public List<SysTenant> queryEffectiveTenant(Collection<Integer> idList) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysTenant::getId, idList);
        queryWrapper.eq(SysTenant::getStatus, Integer.valueOf(CommonConstant.STATUS_1));
        //此处查询忽略时间条件
        return super.list(queryWrapper);
    }

    @Override
    public List<SysTenant> queryTenantsByStatus(Integer status) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getStatus, status);
        //此处查询忽略时间条件
        return super.list(queryWrapper);
    }

    @Override
    public Long countUserLinkTenant(String id) {
        LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(SysUser::getRelTenantIds, id);
        userQueryWrapper.or().like(SysUser::getRelTenantIds, "%," + id);
        userQueryWrapper.or().like(SysUser::getRelTenantIds, id + ",%");
        userQueryWrapper.or().like(SysUser::getRelTenantIds, "%," + id + ",%");
        // 查找出已被关联的用户数量
        return userService.count(userQueryWrapper);
    }

    @Override
    public boolean removeTenantById(String id) {
        // 查找出已被关联的用户数量
        Long userCount = this.countUserLinkTenant(id);
        if (userCount > 0) {
            throw new JeecgBootException("该租户已被引用，无法删除！");
        }
        return super.removeById(Integer.parseInt(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean newTenant(SysTenant tenant) {
        //  根据 先验证有无账号
        // todo 判断参数
        boolean exist = checkAccountExist(tenant.getAccount());
        if(exist) {
            throw new JeecgBootException("账号已存在");
        }
        // todo qh：参数账号密码校验，手机号校验
        save(tenant);
        SysUser adminUser = new SysUser();
        adminUser.setActivitiSync(0);
        adminUser.setUsername(tenant.getAccount());
        adminUser.setRealname(tenant.getUsername());
        adminUser.setRelTenantIds(tenant.getId().toString());
        adminUser.setPhone(tenant.getPhone());
        adminUser.setIsAdmin(1);
        adminUser.setWorkNo(tenant.getAccount());
        String salt = oConvertUtils.randomGen(8);
        adminUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(adminUser.getUsername(), tenant.getPwd(), salt);
        adminUser.setPassword(passwordEncode);
        adminUser.setStatus(1);
        adminUser.setDelFlag(CommonConstant.DEL_FLAG_0);
        //用户表字段org_code不能在这里设置他的值
        adminUser.setOrgCode(null);
        userService.save(adminUser);
        // 获取通用租户权限
        SysRole tRole = roleService.getOne(Wrappers.<SysRole>query().eq("role_code","tenant_role_1"));
        // 关联租户管理员到通用权限
        SysUserRole uRole = new SysUserRole(adminUser.getId(),tRole.getId());
        userRoleService.save(uRole);
        return true;
    }

    private boolean checkAccountExist(String account){
        return userService.getUserByName(account) != null;
    }

}
